package com.sakura.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sakura.seckill.mapper.OrderMapper;
import com.sakura.seckill.mapper.SeckillOrderMapper;
import com.sakura.seckill.pojo.Order;
import com.sakura.seckill.pojo.SeckillGoods;
import com.sakura.seckill.pojo.SeckillOrder;
import com.sakura.seckill.pojo.User;
import com.sakura.seckill.service.ISeckillGoodsService;
import com.sakura.seckill.service.ISeckillOrderService;
import com.sakura.seckill.utils.MD5Util;
import com.sakura.seckill.utils.UUIDUtil;
import com.sakura.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sakura
 * @since 2022-08-16
 */
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {

    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 秒杀
     * @param user
     * @param goods
     * @return
     */
    @Transactional
    @Override
    public Order seckill(User user, GoodsVo goods) {
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //秒杀商品表减库存
        QueryWrapper<SeckillGoods> queryWrapper =new QueryWrapper<>();
        //根据商品id查询商品
        queryWrapper.eq("goods_id",goods.getId());
        SeckillGoods seckillGoods = seckillGoodsService.getOne(queryWrapper);
        //减库存
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);

        //解决库存超卖问题
        //update seckill_goods set stock_count = stock_count - 1 where goods_id = #{goodsId} and stock_count > 0
        UpdateWrapper<SeckillGoods> updateWrapper =new UpdateWrapper<>();
        updateWrapper.setSql("stock_count ="+"stock_count-1")
                        .eq("goods_id",goods.getId())
                                .gt("stock_count",0);
        //更新操作
        boolean result = seckillGoodsService.update(updateWrapper);
//        if(!result){
//            return null;
//        }
        if(seckillGoods.getStockCount()<1){
            //判断是否还有库存
            valueOperations.set("isStockEmpty:"+goods.getId(),0);
            return null;
        }

        //生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        //插入数据库
        orderMapper.insert(order);

        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goods.getId());
        //保存订单
        seckillOrderService.save(seckillOrder);

        return order;
    }

    /**
     * 功能描述：获取秒杀地址
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, Long goodsId) {

        //接口地址随机生成，使用md5加密
        String strPath = MD5Util.md5(UUIDUtil.uuid() + "123456");
        //接口地址存入Redis，失效时间为1分钟
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("seckillPath:"+user.getId()+":"+goodsId,strPath,60, TimeUnit.SECONDS);

        return strPath;
    }

    /**
     * 校验秒杀地址
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public boolean checkPath(User user, Long goodsId,String path) {
        if (user==null || goodsId<0 || StringUtils.isEmpty(path)){
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }

    /**
     * 校验验证码
     * @param user
     * @param goodsId
     * @param captcha
     * @return
     */
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (user==null || goodsId<0 || StringUtils.isEmpty(captcha)){
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }

    /**
     *  功能描述：获取秒杀结果
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public Long getResult(User user, Long goodsId) {
        QueryWrapper<SeckillOrder> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId())
                        .eq("goodsId",goodsId);

        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(queryWrapper);
        if (null!=seckillOrder){
            return seckillOrder.getOrderId();
        }else if(redisTemplate.hasKey("isStockEmpty:"+goodsId)){
            return -1L;
        }else {
            return 0L;
        }
    }
}
